package com.turing.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.turing.common.response.CommonCode;
import com.turing.common.response.ResponseCode;
import com.turing.common.response.ResponseMessage;
import com.turing.common.response.ResponseVO;
import com.turing.common.util.*;
import com.turing.data.inner.DrawTaskInnerService;
import com.turing.data.model.domain.element.Template;
import com.turing.data.service.element.SubProductService;
import com.turing.data.service.element.TemplateIndustryService;
import com.turing.data.service.element.TemplateService;
import com.turing.data.service.element.TemplateTypeService;
import com.turing.data.vo.in.element.TemplateSearchVO;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * @Description 场景controller
 * @Author lcy
 * @Date 2021/6/9 11:16
 */
@Api("场景controller")
@RestController
@RequestMapping("template")
public class TemplateController {

    @Value("${fdfs.domain}")
    private String DOMAIN;

    /**
     * 场景service
     */
    @Autowired
    private TemplateService templateService;

    @Autowired
    private TemplateTypeService templateTypeService;

    @Autowired
    private TemplateIndustryService templateIndustryService;

    @Autowired
    private DrawTaskInnerService drawTaskInnerService;


    /**
     * 通过id获取模板
     * @param templateId 场景id
     * @return com.turing.common.response.ResponseVO<com.turing.draw.model.domain.Template>
     * @author lcy
     * @date 2021/6/11 11:19
     **/
    @GetMapping("getTemplateById")
    public ResponseVO<Template> getTemplateById(@RequestParam("templateId") String templateId){
        return ResponseUtil.success(templateService.getById(templateId));
    }

    /**
     * 通过名称获取场景
     * @param templateName 场景名称
     * @return com.turing.common.response.ResponseVO<com.turing.draw.model.domain.Template>
     * @author lcy
     * @date 2021/6/11 11:19
     **/
    @GetMapping("getTemplateByName")
    public ResponseVO<Template> getTemplateByName(String templateName){
        LambdaQueryWrapper<Template> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Template :: getTemplateName,templateName);
        return ResponseUtil.success(templateService.getOne(queryWrapper));
    }

    /**
     * 通过名称获取所有场景
     * @param templateName 场景名称
     * @return com.turing.common.response.ResponseVO<com.turing.draw.model.domain.Template>
     * @author lcy
     * @date 2021/6/11 11:19
     **/
    @GetMapping("getAllTemplateByName")
    public List<Template> getAllTemplateByName(@RequestParam(required = false) String templateName){
        LambdaQueryWrapper<Template> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(templateName).filter(StringUtils::isNotEmpty).ifPresent(t -> queryWrapper.like(Template::getTemplateName, t));
        return templateService.list(queryWrapper);
    }


    /**
     * 获取产品合同所有场景id
     * @return com.turing.common.response.ResponseVO<java.util.List < java.lang.String>>
     * @author lcy
     * @date 2021/6/9 11:29
     **/
    @GetMapping("getProductTemplate")
    ResponseVO<Set<String>> getProductTemplate(){
        return ResponseUtil.success(templateService.getProductTemplate());
    }

    /**
     * 获取具有权限的场景id
     * @return com.turing.common.response.ResponseVO<java.util.List < java.lang.String>>
     * @author lcy
     * @date 2021/6/9 11:29
     **/
    @GetMapping("getPrivilegeTemplate")
    ResponseVO<Set<String>> getPrivilegeTemplate(){
        return ResponseUtil.success(templateService.getPrivilegeTemplate());
    }

    /**
     * 开启/关闭场景的自动审核
     * @param templateSn 场景id
     * @return com.turing.common.response.ResponseVO<java.lang.Object>
     * @author lcy
     * @date 2021/6/11 10:46
     **/
    @PostMapping("optionAutoAudit")
    public ResponseVO<Object> optionAutoAudit(@RequestParam Integer autoAudit, @RequestParam String templateSn){
        return templateService.optionAutoAudit(autoAudit,templateSn) ? ResponseUtil.success() : ResponseUtil.create(CommonCode.FAIL);
    }

    /**
     * 查询-存在的要素抽取 | 选择场景
     * @param templateSearchVO
     * @return
     */
    @PostMapping("queryByCondition")
    public ResponseVO<Object> queryByCondition(@RequestBody TemplateSearchVO templateSearchVO){
        return ResponseUtil.success(templateService.queryByCondition(templateSearchVO));
    }

    /**
     * 要素抽取 | 要素抽取 | 选择场景
     * @return
     */
    @GetMapping("getTypeDic")
    public ResponseVO<Object> getTypeDic(){

        return ResponseUtil.success(templateTypeService.list());

    }

    /**
     * 要素抽取 | 选择场景 行业类型
     * @return
     */
    @GetMapping("getIndustryDic")
    public ResponseVO<Object> getIndustryDic(){

        return ResponseUtil.success(templateIndustryService.list());

    }

    @PostMapping("uploadPic")
    public ResponseVO<Object> uploadPic(@RequestParam("file") MultipartFile file){

        try {
            String typeByFile = FileTypeUtil.getTypeByStream(file.getInputStream());
            if(StringUtils.isEmpty(typeByFile)){
                typeByFile = FileTypeUtil.getTypeBySuffix(Objects.requireNonNull(file.getOriginalFilename()));
            }
            if(typeByFile.equals("jpg")){
                return ResponseUtil.success(FdfsUtils.uploadMultipartFile(file));
            }else if(typeByFile.equals("png")){
                BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
                        bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);

                newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

                // write to jpeg file
                ImageIO.write(newBufferedImage, "jpg", new File("/tmp/"+ UUID.randomUUID().toString() + ".jpg"));
                return ResponseUtil.success(FdfsUtils.uploadMultipartFile(file));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseUtil.error();

    }

    @PostMapping("getPicByUrl")
    public ResponseVO<Object> getPicByUrl( @RequestParam("url") String url){

        File file = FileUtils.downloadFile(DOMAIN + url);
        try{
            //String type = FileTypeUtil.getTypeByFile(file);
            FileInputStream is=new FileInputStream(file);
            //response.setContentType("image/jpeg");

            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            // 读取图片字节数组
            try {

                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = is.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
                //response.getWriter().write(Arrays.toString(data));
                is.close();
                swapStream.flush();
                swapStream.close();
                //response.getWriter().close();
                return ResponseUtil.create(ResponseCode.SUCCESS,ResponseMessage.SUCCESS,0, Base64.getEncoder().encodeToString(data));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseUtil.create(ResponseCode.TEXT_NULL,ResponseMessage.TEXT_NULL,1,"");
    }

    @GetMapping("getSubProductsByTemplate")
    public ResponseVO<Object> getSubProductsByTemplate( @RequestParam("taskSn") String taskSn ){

        String taskTemplate = drawTaskInnerService.getTaskTemplate(taskSn);
        return ResponseUtil.success( templateService.getSubProducts(taskTemplate) );

    }

    @GetMapping("cvModelOnline")
    public ResponseVO<Boolean> CVOnline(  ){

        return ResponseUtil.success( templateService.CVOnline() );

    }


}
